//
//  HNTeacherAttenceVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/12/5.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNTeacherAttenceVC.h"
#import "HMTeacherAttendanceRecordVC.h"


@interface HNTeacherAttenceVC ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    __weak IBOutlet UIView *_HideView;
    __weak IBOutlet UIActivityIndicatorView *_Activity;
    
    __weak IBOutlet UILabel *_TimeDes; // 时间描述
    __weak IBOutlet UILabel *_OrgDes; // 机构描述
    __weak IBOutlet UILabel *_SignDes; // 签到描述
    __weak IBOutlet UIView *_SignImgView; // 需要与请假事由相互隐藏
    __weak IBOutlet UIView *_SignLeaveView; // 需要与签到相互隐藏
    __weak IBOutlet UILabel *_SignTime; // 签到的年月日
    __weak IBOutlet UILabel *_SignOrg; // 签到的机构
    __weak IBOutlet UIButton *_SignImg; // 签到的图片
    __weak IBOutlet UILabel *_SignSureTime; // 签到的时分
    __weak IBOutlet UIView *_SignSureView; // 签到的按钮的父视图，形变用
    __weak IBOutlet UIButton *_SignSureBtn; // 签到、请假按钮
    __weak IBOutlet UITextView *_LeaveTextView; // 请假事由
    
    BOOL _SignState; // 签到状态 
    BOOL _LeaveState; // 请假状态
    BOOL _SignLeave; // 签到还是请假状态 YES签到 NO 请假
}


@end

@implementation HNTeacherAttenceVC


#pragma mark - 生命周期
- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    // 变圆
    _SignSureView.layer.cornerRadius = _SignSureView.frame.size.width / 2;
    _SignSureView.layer.masksToBounds = YES;
    // 加框
    _LeaveTextView.layer.cornerRadius = 10.f;
    _LeaveTextView.layer.masksToBounds = YES;
    _LeaveTextView.layer.borderColor = [ColorRGB(200, 200, 2000) CGColor];
    _LeaveTextView.layer.borderWidth = 1.f;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"考勤";
    
    UIButton *Button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [Button setTitle:@"考勤记录" forState:(UIControlStateNormal)];
    [Button setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    Button.titleLabel.font = [UIFont systemFontOfSize:14.f * KScale];
    [Button addTarget:self action:@selector(GoHistory) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:Button];

    
    // 时间跳动
    [self MgrTimeOfHourAndMinWithCallBack:^(NSString *Hour, NSString *Min) {
        
        _SignSureTime.text = [NSString stringWithFormat:@"%@:%@", Hour, Min];
    }];
    
    // 获取签到请假状态
    [self RefreshDataForStateWithCallBack:^(BOOL SignState, BOOL LeaveState) {
       
        _SignState = SignState;
        _LeaveState = LeaveState;
        // 点击了底部签到按钮
        [self SegmentChange:(UIButton *)[self.view viewWithTag:1100]];
    }];
}
#pragma mark 生命周期End




#pragma mark - 网络
/** 获取签到请假状态 */
- (void)RefreshDataForStateWithCallBack:(void (^)(BOOL SignState, BOOL LeaveState))CallBack {
    
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:@{@"action":@"teacherIsSign"} Success:^(id Obj) {
        
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            _SignOrg.text = ![Obj[@"t"][@"websiteName"] isKindOfClass:[NSNull class]] ? Obj[@"t"][@"websiteName"]:@"";
            _SignTime.text = [self GetTime:NO];
            // num签到状态 param请假状态
            CallBack ? CallBack ([Obj[@"t"][@"num"] isEqualToNumber:@0]?NO:YES, [Obj[@"t"][@"param"] isEqualToNumber:@0]?NO:YES):nil;
            [_HideView removeFromSuperview];
        } else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
            [_Activity stopAnimating];
        }
    } Fail:^(NSError *Error) {
        [SVProgressHUD showErrorWithStatus:NetErr];
        [_Activity stopAnimating];
    }];
}

- (void)RefreshDataForSureOfType:(NSNumber *)Type andImg:(UIImage *)Img andReason:(NSString *)Reason hud:(MBProgressHUD *)hud CallBack:(void (^)())CallBack {
    
    NSDictionary *Params = @{
                             @"action":@"saveTeacherRecord",
                             @"type":Type,
                             @"reason":Reason
                             };
    [NetManager UpdataImgsWithURL:LLBaseURL(@"yxhUser.do") imgs:(Img ? @[Img]:nil) parameter:Params Progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (uploadProgress.totalUnitCount == uploadProgress.completedUnitCount)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [hud setHidden:YES];
                [HUD showHUD];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                hud.label.text = [NSString stringWithFormat:@"总大小：%.2fM,当前大小:%.2fM",uploadProgress.totalUnitCount/1024.0/1024.0,uploadProgress.completedUnitCount/1024.0/1024.0];
            });
        }
        
    }success:^(id obj) {
        
        [hud setHidden:YES];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingMutableLeaves error:nil];
        if ([dict[@"code"] isEqualToNumber:@1000])
        {
            if (CallBack)
            {
                CallBack ();
            }
        }
        else
        {
            [HUD showError:dict[@"msg"]];
        }
    } fail:^(NSError *error) {
        [hud setHidden:YES];
        [HUD showError:NetErr];
    }];
}
#pragma mark 网络End


#pragma mark - 签到签到的方法
/** 签到或请假 */
- (IBAction)SignSure:(UIButton *)sender {
    
    [_LeaveTextView resignFirstResponder];
    UIAlertController *Alert = [UIAlertController alertControllerWithTitle:(_SignLeave ? @"是否确认签到?":@"是否确认请假?") message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    [Alert addAction:[UIAlertAction actionWithTitle:(_SignLeave ? @"签到":@"请假") style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        [self RefreshDataForSureOfType:(_SignLeave ? @0:@1) andImg:(_SignLeave ? (_SignImg.selected ? _SignImg.currentBackgroundImage:nil):nil) andReason:(_SignLeave ? @"":_LeaveTextView.text) hud:[self HUD] CallBack:^{
            
            [HUD showSuccess:_SignLeave ? @"签到成功":@"请假成功"];
            if (_SignLeave) {
                
                _SignState = YES;
            } else {
                
                _LeaveState = YES;
            }
            [self SegmentChange:(UIButton *)[self.view viewWithTag:_SignState ? 1100:1101]];
            
        }];
    }]];
    [Alert addAction:[UIAlertAction actionWithTitle:@"放弃" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:Alert animated:YES completion:nil];
}

/** 上传图片 */
- (IBAction)UpLoadImg:(UIButton *)sender {
    // 根据状态选择不同处理
    sender.selected ? [self DeleteImg:sender]:[self AlertController:nil];
}
#pragma mark 签到请假的方法End





#pragma mark - 底部切换
/** 点击不同的按钮 */
- (IBAction)SegmentChange:(UIButton *)sender {
    
    // 取出两个按钮
    UIButton *FirstButton = (UIButton *)[self.view viewWithTag:1100];
    UIButton *SecondButton = (UIButton *)[self.view viewWithTag:1101];
    // 根据状态切换
    // 点击的是签到
    if (sender.tag == 1100) {
        
        FirstButton.selected = YES;
        SecondButton.selected = NO;
        _SignLeave = YES;
        self.title = @"考勤";
        [self.view bringSubviewToFront:_SignImgView];
        [self ConfigUIWithIsSign:YES];
    }
    // 点击的是请假
    if (sender.tag == 1101) {
        
        FirstButton.selected = NO;
        SecondButton.selected = YES;
        _SignLeave = NO;
        self.title = @"请假";
        [self.view bringSubviewToFront:_SignLeaveView];
        [self ConfigUIWithIsSign:NO];
    }
}

/** IsSign:YES签到 NO请假 */
- (void)ConfigUIWithIsSign:(BOOL)IsSign {
    // 时间、机构、签到/请假
    _TimeDes.text = IsSign ? @"签到日期:":@"请假日期:";
    _OrgDes.text  = IsSign ? @"签到机构:":@"所在机构:";
    _SignDes.text = IsSign ? _SignState ? @"已签到":@"签到" : _LeaveState ? @"已请假":@"请假";
    _SignSureBtn.enabled = IsSign ? _SignState ? NO:YES : _LeaveState ? NO:YES;
    // 中间的选项View相互隐藏
    [UIView animateWithDuration:0.3f animations:^{
        _SignImgView.alpha = IsSign ? 1:0;
        _SignLeaveView.alpha = IsSign ? 0:1;
    }];
}
#pragma mark 底部切换End





#pragma mark - Func
/** 前往考勤记录 */
- (void)GoHistory {
    
    HMTeacherAttendanceRecordVC *vc = [HMTeacherAttendanceRecordVC new];
    
    [self.navigationController pushViewController:vc animated:YES];
    
}
/** 获取年月日时分秒: YES时:分:秒  NO年月日*/
- (NSString *)GetTime:(BOOL)Is {
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitWeekday | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:[NSDate date]];
    NSInteger Year = comps.year;
    NSInteger Mon = comps.month;
    NSInteger Day = comps.day;
    NSInteger Hour = comps.hour;
    NSInteger Min = comps.minute;
    NSInteger Sec = comps.second;
    return Is ? [NSString stringWithFormat:@"%ld:%ld:%ld",Hour, Min, Sec]:[NSString stringWithFormat:@"%ld-%ld-%ld",Year, Mon, Day];
}

/** 只显示时:分，但秒要计算 */
- (void)MgrTimeOfHourAndMinWithCallBack:(void (^)(NSString *Hour, NSString *Min))CallBack {
    
    // 获取时分秒: 时:分:秒
    NSArray *TimeArr = [[self GetTime:YES] componentsSeparatedByString:@":"];
    __block NSInteger hour = [TimeArr[0] integerValue];
    __block NSInteger min = [TimeArr[1] integerValue];
    // 先把时间传出去
    CallBack ? CallBack ((hour >= 10 ? [@(hour) stringValue]:[NSString stringWithFormat:@"0%ld", min]), (min >= 10 ? [@(min) stringValue]:[NSString stringWithFormat:@"0%ld",min])):nil;
    // 开始计算秒
    [NSTimer scheduledTimerWithTimeInterval:60.f repeats:YES block:^(NSTimer * _Nonnull timer) {
        
        min += 1;
        if (min == 60) {
            min = 0;
            hour += 1;
            if (hour == 24) {
                hour = 0;
            }
        }
        // 传送时间
        CallBack ? CallBack ((hour >= 10 ? [@(hour) stringValue]:[NSString stringWithFormat:@"0%ld", min]), (min >= 10 ? [@(min) stringValue]:[NSString stringWithFormat:@"0%ld",min])):nil;
    }];
}


/** AlertController 增加图片*/
- (void)AlertController:(void (^)(UIImage *img))Complete
{
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self ConfigImagePickController:YES];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"从相册中选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self ConfigImagePickController:NO];
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:AlertController animated:YES completion:nil];
}

/** 删除按钮上的图片 */
- (void)DeleteImg:(UIButton *)Button
{
    UIAlertController *AlertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"是否删除已上传的图片?" preferredStyle:(UIAlertControllerStyleActionSheet)];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"删除" style:(UIAlertActionStyleDestructive) handler:^(UIAlertAction * _Nonnull action) {
        _SignImg.selected = NO;
    }]];
    [AlertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:AlertController animated:YES completion:nil];
}

/** 初始相机与相册 ,根据isCamera调用相机或相册*/
- (void)ConfigImagePickController:(BOOL)isCamera
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = isCamera ? UIImagePickerControllerSourceTypeCamera:UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:^{

        _SignImg.selected = YES;
        [_SignImg setBackgroundImage:img forState:(UIControlStateSelected)];
    }];
}

- (MBProgressHUD *)HUD
{
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    HUD.mode = MBProgressHUDModeText;
    HUD.removeFromSuperViewOnHide = YES;
    HUD.backgroundColor = ColorRGBA(0, 0, 0, 0.5);
    HUD.bezelView.color =[UIColor blackColor];
    HUD.contentColor = [UIColor whiteColor];
    HUD.label.text = @"正在上传中...0%";
    return HUD;
}
#pragma mark FuncEnd
@end
